/*
 * Copyright 1999-2010 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.aone.casestudy.module.control;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.intl.commons.framework.dto.BaseQuery;

/**
 * 类Pagination.java的实现描述：TODO 类实现描述
 * 
 * @author gaojian 2011-4-29 上午11:21:46
 */
public class Pagination {

	private static final Integer DEFAULT_PAGINATION_SIZE = new Integer(10);
	private static final Integer DEFAULT_PAGINATION_MIDDLE_POSITION = new Integer(
			6);

	public void execute(Context context) {
		Integer paginationSize = (Integer) context.get("paginationSize");
		Integer paginationMidPosition = DEFAULT_PAGINATION_MIDDLE_POSITION;
		if (paginationSize == null || paginationSize <= 0) {
			paginationSize = DEFAULT_PAGINATION_SIZE;
		} else {
			paginationMidPosition = (paginationSize / 2) + 1;
		}

		BaseQuery query = (BaseQuery) context.get("query");
		if (query == null) {
			return;
		}
		int currentPage = query.getCurrentPage().intValue();
		int totalPage = query.getTotalPage();

		int begin = 2;
		if (currentPage > paginationMidPosition.intValue()) {
			begin = currentPage - paginationMidPosition.intValue() + 1;
		}

		int end = begin + paginationSize.intValue() - 1;
		if (end > totalPage - 1) {
			end = totalPage - 1;
		}

		if (currentPage < totalPage) {
			context.put("next", new Integer(currentPage + 1));
			if (currentPage + 10 <= totalPage) {
				context.put("nextTen", new Integer(currentPage + 10));
			} else {
				context.put("nextTen", new Integer(totalPage));
			}
		} else {
			context.put("next", null);
		}

		if (currentPage > 1) {
			context.put("previous", new Integer(currentPage - 1));
			if (currentPage - 10 >= 1) {
				context.put("previousTen", new Integer(currentPage - 10));
			} else {
				context.put("previousTen", new Integer(1));
			}
		} else {
			context.put("previous", null);
		}

		context.put("paginationSize", paginationSize);
		context.put("begin", new Integer(begin));
		context.put("end", new Integer(end));
		context.put("current", new Integer(currentPage));
		context.put("totalPage", new Integer(totalPage));
	}

}
